package org.jeecg.modules.system.controller;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.DbanInfoStatusEnum;
import org.jeecg.modules.system.entity.DbanInformation;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.DbanAuthRecordMapper;
import org.jeecg.modules.system.mapper.DbanInformationMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dban/statistics")
public class DbanStatisticsController {

    @Autowired
    private DbanInformationMapper dbanInformationMapper;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private DbanAuthRecordMapper dbanAuthRecordMapper;

    /**
     * 统计
     */
    @GetMapping("info")
    public Result<?> statisticsInfo(Integer year) {

        Map<String, Object> mapResult = new LinkedHashMap<>(16);
        //时间轴
        List<Integer> yearList = dbanInformationMapper.groupByYear();
        mapResult.put("timeLine", yearList);
        //所有地市
        List<SysDepart> sysDeparts = sysDepartService.queryChildDepart();
        //省级部门
        List<SysDepart> parentDepart = sysDepartService.queryParentDepart();
        SysDepart sysDepartParent = parentDepart.get(0);//辽宁省的ID
        String shengJiId = sysDepartParent.getId();
        // mapData: [{city: '沈阳市', code: '120000',total: 1200, recheck: 100  }], // 地图中各地市以及数据信息
        DbanInformation information = new DbanInformation();
        if (year != null) {
            information.setYear(year);
        }
        //只统计发布成功的数据
        information.setStatus(DbanInfoStatusEnum.RELEASE_SUCCESS.value());
        List<DbanInformation> informations = dbanInformationMapper.queryDbanInfomation(information);
        //地图数据
        List<Map<String, Object>> mapDataList = new ArrayList<>();
        //柱状图数据
        List<Map<String, Object>> barDataList = new ArrayList<>();
        //地级复审次数
        List<Map<String, Object>> diJiRepeatMapList = dbanAuthRecordMapper.diShiRepeatCount();
        Map<Integer, Long> diJiRepeatMap = new HashMap<>();
        diJiRepeatMapList.forEach(index -> diJiRepeatMap.put((Integer) index.get("pk_id"), (Long) index.get("count")));
        //省级复审次数
        List<Map<String, Object>> shengJiRepeatMapList = dbanAuthRecordMapper.shengJiRepeatCount();
        Map<Integer, Long> shengJiRepeatMap = new HashMap<>();
        shengJiRepeatMapList.forEach(index -> shengJiRepeatMap.put((Integer) index.get("pk_id"), (Long) index.get("count")));
        int sumDiJiRepeatCount = 0;//复审总数diji
        int sumShengJiRepeatCount = 0;//复审总数省级
        String topCity = "";
        int countDown = 0;//省级外层只需要循环一遍
        //明星城市
        Map<String, Integer> starMap = new HashMap<>();
        for (SysDepart item : sysDeparts) {
            countDown++;//计数
            String id = item.getId();
            String deptName = item.getDepartName();
            //地图
            Map<String, Object> mapDi = new HashMap<>(4);
            //柱状图
            Map<String, Object> barMap = new HashMap<>(4);
            int total = 0;
            int diJiRecheckCount = 0;
            int barTotal = 0;
            int barDijiRecheckCount = 0;
            for (DbanInformation index : informations) {
                String deptIds = index.getDeptIds();
                Integer pkId = index.getId();
                String location = index.getLocation();
                List<String> listDept = Arrays.asList(deptIds.split(","));
                //柱状图
                if (listDept.contains(id)) {
                    barTotal++;
                    barDijiRecheckCount += diJiRepeatMap.get(pkId) == null ? 0 : diJiRepeatMap.get(pkId);
                }
                //地图
                if (StringUtils.isNotBlank(location) && location.contains(deptName)) {//模糊匹配
                    total++;
                    diJiRecheckCount += diJiRepeatMap.get(pkId) == null ? 0 : diJiRepeatMap.get(pkId);
                }
                //省级外层只需要循环一遍
//                if (listDept.contains(shengJiId) && countDown == 1) {
                if (deptName.contains("辽宁省") && countDown == 1) {
                    sumShengJiRepeatCount += shengJiRepeatMap.get(pkId) == null ? 0 : shengJiRepeatMap.get(pkId);
                }
            }
            sumDiJiRepeatCount += diJiRecheckCount;
            //地图
            mapDi.put("city", item.getDepartName());
            mapDi.put("code", item.getOrgCode());
            mapDi.put("total", total);
            mapDi.put("recheck", diJiRecheckCount);
            mapDataList.add(mapDi);
            //柱状图
            barMap.put("city", item.getDepartName());
            barMap.put("code", item.getOrgCode());
            barMap.put("total", barTotal);
            barMap.put("recheck", barDijiRecheckCount);
            barDataList.add(barMap);
            starMap.put(item.getDepartName(), total);
        }
        mapResult.put("mapData", mapDataList);
        //柱状图统计
        mapResult.put("barData", barDataList);
        //总资产数（算了省级的，地图中没有统计省级的数量，所以两者加起来不会相等）
        mapResult.put("total", informations.size());
        mapResult.put("recheck", sumDiJiRepeatCount + sumShengJiRepeatCount);
        //明星城市
        starMap.put(sysDepartParent.getDepartName(), sumShengJiRepeatCount);
        Map<String, Integer> stringIntegerMap = valueUpSort(starMap);
        for (Map.Entry<String, Integer> index : stringIntegerMap.entrySet()) {
            String key = index.getKey();
            mapResult.put("startCity", key);
            break;
        }
        //五个一批好成果统计
        wugeyipihcg(mapResult);
        //热点主题
        subjectTop5(year, mapResult, informations);
        //文件top5
        queryTop5("文件", year, mapResult, "hotFile");
        //文章top5
        queryTop5("文章", year, mapResult, "hotArticle");
        //图片top5
        queryTop5("图片", year, mapResult, "hotImage");
        //视频top5
        queryTop5("视频", year, mapResult, "hotVideo");
        //音频top5
        queryTop5("音频", year, mapResult, "hotAudio");
        //图书top5
        queryTop5("图书", year, mapResult, "hotBook");
        return Result.ok(mapResult);
    }


    /**
     * 五个一批好成果分类和top5
     * fiveTypeStatic: [{name: '教材', value: 1000}, {name: '教学课程', value: 1000}], // 五个一批好成果各类型数量
     * hotFive: [{title: '五个一批好成果热点', id: '1'}], // 五个一批好成果热点top5
     */
    public void wugeyipihcg(Map<String, Object> mapResult) {
        //统计
        DbanInformation information = new DbanInformation();
        information.setType("五个一批好成果");
        information.setStatus(DbanInfoStatusEnum.RELEASE_SUCCESS.value());
        List<DbanInformation> informations = dbanInformationMapper.queryDbanInfomation(information);
        Map<String, List<DbanInformation>> fiveOneTypeMap = informations.stream().collect(Collectors.groupingBy(DbanInformation::getFiveOneType));
        List<Map<String, Object>> fiveTypeStatic = new ArrayList<>();
        for (Map.Entry<String, List<DbanInformation>> index : fiveOneTypeMap.entrySet()) {
            Map<String, Object> fiveTypeStaticMap = new HashMap<>(2);
            fiveTypeStaticMap.put("name", index.getKey());
            fiveTypeStaticMap.put("value", index.getValue().size());
            fiveTypeStatic.add(fiveTypeStaticMap);
        }
        mapResult.put("fiveTypeStatic", fiveTypeStatic);
        //热点
        List<DbanInformation> dbanInformations = dbanInformationMapper.wgyhcgHeat();
        List<Map<String, Object>> hotFiveList = new ArrayList<>();
        for (DbanInformation index : dbanInformations) {
            Map<String, Object> hotFilve = new HashMap<>(2);
            hotFilve.put("title", index.getName());
            hotFilve.put("id", index.getId());
            hotFiveList.add(hotFilve);
        }
        mapResult.put("hotFive", hotFiveList);
    }

    /**
     * 主题top5
     * hotTheme: [{name: '主题1', id: '1',count:11}], // 热点主题列表top5
     *
     * @return
     */
    public void subjectTop5(Integer year, Map<String, Object> mapResult, List<DbanInformation> informations) {

        List<DbanInformation> sujectInfo = dbanInformationMapper.subjectHeat(year);
        List<Map<String, Object>> list = new ArrayList<>();
//        Map<String, List<DbanInformation>> collect = informations.stream().filter(index -> StringUtils.isNotBlank(index.getSubject())).collect(Collectors.groupingBy(DbanInformation::getSubject));
        for (DbanInformation index : sujectInfo) {
            Map<String, Object> map = new HashMap<>(3);
            map.put("name", index.getSubject());
            map.put("id", index.getId());
            map.put("count", index.getViewCount());
            list.add(map);
        }
        mapResult.put("hotTheme", list);
    }


    /**
     * 查询文章、文件等资源的top5
     * hotFile: [{name: '文件', id: '1'}], // 热点文件top5
     * hotArticle: [{name: '文章', id: '1'}], // 热点文章top5
     * hotImage: [{name: '图片', id: '1'}], // 热点图片top5
     * hotVideo: [{name: '视频', id: '1'}], // 热点视频top5
     * hotAudio: [{name: '音频', id: '1'}],// 热点音频top5
     * hotBook: [{name: '图书', id: '1'}] // 热点图书top5
     *
     * @return
     */
    public void queryTop5(String type, Integer year, Map<String, Object> mapResult, String key) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<DbanInformation> dbanInformations = dbanInformationMapper.queryTop(year, type);
        for (DbanInformation index : dbanInformations) {
            Map<String, Object> map = new HashMap<>(2);
            map.put("name", index.getName());
            map.put("id", index.getId());
            list.add(map);
        }
        mapResult.put(key, list);
    }

    //Map根据value进行排序
    public static Map<String, Integer> valueUpSort(Map<String, Integer> map) {

        //map不能为空
        if (map == null || map.isEmpty()) {
            return null;
        }
        //定义一个LinkedHashMap
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();

        List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        //比较器
        Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //降序
                return o2.getValue().compareTo(o1.getValue());
                //升序
//                return o2.getValue().compareTo(o1.getValue());
            }
        });

        Iterator<Map.Entry<String, Integer>> iter = entryList.iterator();
        Map.Entry<String, Integer> tmpEntry = null;
        while (iter.hasNext()) {
            tmpEntry = iter.next();
            sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());
        }
        return sortedMap;
    }


}
